<template>
  <!-- 用于测试滚动条 可删除 -->
  <div>
    <!-- <span @click="get_postdata()">提交的数据</span> -->
    <!-- <span @click="resetSpectext()">清楚数据</span> -->

    <div v-for="(ever, index) in specsArr">
      <!-- 规格报错提示块 -->
      <div v-if="ever.sku_error.length > 0" class="sku__error error_red_box">
        <el-icon style="margin-right: 6px; font-size: 14px; position: relative; top: 2px"><WarningFilled /></el-icon>
        {{ $t("goods_archive.current_system_model_sku") }}
        <span v-for="(tip, index) in ever.sku_error">
          {{ sku_error_tips[tip] }}<i v-if="!index == ever.sku_error.length - 1"> , </i>
        </span>
      </div>
      <div class="specs_ever">
        <div class="header">
          <div style="display: flex; align-items: center">
            <span class="" style="position: relative; top: 1px"
              >{{ $t("goods_archive.sku_product") }}
              <el-tooltip popper-class="merak-control-tip-popper" placement="top">
                <el-icon>
                  <info-filled />
                </el-icon>
                <template #content>
                  <div>
                    <p>
                      SPU，Standard Product Unit
                      标准化产品单元，是商品信息聚合的最小单位，是一组可复用、易检索的标准化信息的集合，该集合描述了商品的特性。其属性值、特性相同的商品都可以称为一个SPU。通俗点讲，属性值、特性相同的商品就可以称为一个SPU。
                    </p>
                    <p>
                      SKU，Stock Keeping
                      Unit库存量单位，用来定价和管理库存，例如服装，同款可以有不同的尺码，不同的颜色这些都是独立的SKU。
                    </p>
                    <p>总结:SPU是一个商品,而SKU是该商品的不同的规格。</p>
                  </div>
                </template>
              </el-tooltip></span
            >
            <div style="margin-left: 8px">
              <el-input
                @change="check_sku(ever, ever.fvalue.sku, index)"
                @input="ever.fvalue.sku = ever.fvalue.sku.replace(/[^a-zA-Z0-9\-\_]/g, '')"
                v-model="ever.fvalue.sku"
                class="qifa_input sku"
                style="width: 240px"
              >
                {{ props.sku_before }}
                <template v-if="props.sku_before" #prefix>{{ props.sku_before + "-" }}</template>
              </el-input>
            </div>
          </div>
          <div>
            <el-button type="primary" @click="addspecs('copy', ever)" link style="padding: 0; min-width: auto">
              {{ $t("merak.copy") }}
            </el-button>

            <el-button disabled type="default" v-if="specsArr.length < 2" link style="padding: 0; min-width: auto">
              删除
            </el-button>
            <el-button type="danger" v-else @click="delspecs(index)" link style="padding: 0; min-width: auto"> 删除 </el-button>
          </div>
        </div>

        <div class="body">
          <el-form :ref="el => (refs[index] = el)" :model="ever.fvalue">
            <el-row :gutter="40">
              <el-col v-for="item in ever.Items" :span="props.span">
                <MerakControl v-bind="item" v-model="ever.fvalue[item.field]" :query-options="handleQueryOptions">
                  <!-- 货号体积(m³) -->
                  <template #volume>
                    <el-input
                      class="qf_input"
                      type="text"
                      @blur="changeVolume(ever.fvalue.volume, ever)"
                      v-num.point
                      v-model="ever.fvalue.volume"
                    />
                  </template>

                  <!-- 企发颜色 -->
                  <template #qifa_color_id>
                    <el-select
                      filterable
                      @change="colorfun(ever, index)"
                      value-key="id"
                      class="qf_select"
                      :placeholder="$t('merak.placeholder_select')"
                      v-model="ever.fvalue.qifa_color_id"
                    >
                      <!-- 数量小于1，或者套装，不要多色 -->
                      <template v-if="ever.fvalue.num_in_packing < 2 || props.suite == 1">
                        <el-option
                          :label="item.label"
                          :value="item.value"
                          v-for="item in item.options.filter(v => v.value != '251')"
                          :key="item"
                        />
                      </template>
                      <!-- 需要多色 -->
                      <template v-else>
                        <el-option :label="item.label" :value="item.value" v-for="item in item.options" :key="item" />
                      </template>
                    </el-select>
                  </template>

                  <!-- 商家颜色 -->
                  <template #supplier_color_id>
                    <el-select
                      filterable
                      value-key="id"
                      class="qf_select"
                      :placeholder="$t('merak.placeholder_select')"
                      v-model="ever.fvalue.supplier_color_id"
                      :disabled="item.disabled"
                    >
                      <el-option :label="item.label" :value="item.value" v-for="item in props.spmColors" :key="item" />
                    </el-select>
                  </template>

                  <!-- 外包装内数量 -->
                  <template #num_in_packing>
                    <el-input
                      :disabled="props.id == '14'"
                      @input="change_num_inpaking(ever, ever.fvalue.num_in_packing, index)"
                      class="qf_input"
                      type="text"
                      v-number
                      v-model="ever.fvalue.num_in_packing"
                    />
                  </template>

                  <!-- 无尺码有多色 -->
                  <template #more_color>
                    <div :span="6" class="create_size_box">
                      <el-popover
                        placement="bottom"
                        width="400"
                        trigger="click"
                        popper-class="own_popper own_popper_big"
                        :visible="ever.popoverVisible"
                        @show="sizeMiniShow(ever, ever.sizeMiniData.dataValue)"
                        @hide="sizeMiniHide(ever, ever.sizeMiniData.dataValue)"
                      >
                        <template #reference>
                          <div
                            class="el-input el-input--default qf_input"
                            @click="ever.popoverVisible = !ever.popoverVisible"
                            v-click-outside="onClickOutside"
                          >
                            <div class="el-input__wrapper">
                              <div class="el-input__inner">
                                {{ ever.fvalue.more_color }}
                                <el-input type="hidden" v-model="ever.fvalue.more_color" />
                              </div>
                            </div>
                          </div>
                        </template>
                        <div class="size_table_box">
                          <editTableMini
                            v-bind="ever.sizeMiniData"
                            @plusCol="plusCol(ever.sizeMiniData.dataValue, 'minisize')"
                            @delOne="index => delOne(index, ever.sizeMiniData.dataValue, 'minisize', ever)"
                          >
                            <!-- 尺码插槽 -->
                            <template #size="{ scoped }">
                              <div>--</div>
                            </template>
                            <!-- 颜色插槽 -->
                            <template #color="{ scoped }">
                              <div v-if="ever.fvalue.qifa_color_id == '251'">
                                <el-select
                                  filterable
                                  :validate-event="false"
                                  value-key="id"
                                  class="qf_select"
                                  :placeholder="$t('merak.placeholder_select')"
                                  v-model="scoped.row.color"
                                  popper-class="own_popper"
                                >
                                  <el-option
                                    :label="item.label"
                                    :value="item.value"
                                    v-for="item in colors.filter(item => item.value != '251')"
                                    :key="item"
                                  />
                                </el-select>
                              </div>

                              <div v-else style="line-height: 24px">
                                <span v-if="ever.fvalue.qifa_color_id">
                                  {{ colors.filter(v => v.value == ever.fvalue.qifa_color_id).map(v => v.label)[0] }}
                                </span>
                              </div>
                            </template>

                            <template #num="{ scoped }">
                              <div>
                                <el-input
                                  @change="mini_size_all_change(ever.sizeMiniData.dataValue, ever, scoped.row.num)"
                                  v-number
                                  :validate-event="false"
                                  class="editCon"
                                  v-model="scoped.row.num"
                                ></el-input>
                              </div>
                            </template>
                          </editTableMini>
                        </div>
                        <!-- <div  style="display: flex; justify-content: center;margin-top:6px;"> {{$t("goods_archive.now_num_all")}}: {{specsArr[0].mini_size_all_num}}</div> -->

                        <div class="error_tip">{{ ever.size_tip }}</div>
                        <div style="display: flex; justify-content: center">
                          <el-button type="primary" plain @click="savesize(ever)">
                            {{ $t("goods_archive.size_btn_save") }}</el-button
                          >
                        </div>
                      </el-popover>
                    </div>
                  </template>

                  <template #size>
                    <!-- 规格类型 spec_type 1 文本 -->
                    <div v-if="props.formConfig.spec_type == 1" class="create_size_box">
                      <el-dropdown trigger="click" style="width: 100%">
                        <div class="el-dropdown-link" style="width: 100%">
                          <div class="el-input el-input--default qf_input">
                            <div class="el-input__wrapper">
                              <div class="el-input__inner">{{ ever.fvalue.size }}</div>
                            </div>
                          </div>
                        </div>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <div style="margin: 20px">
                              <el-input
                                class="qf_input"
                                :validate-event="false"
                                v-model="ever.fvalue.size_cn"
                                @change="mergeSizeFun(ever.fvalue.size_cn, ever.fvalue.size_ru, ever)"
                                style="max-width: 600px"
                              >
                                <template #prepend> {{ $t("goods_archive.spec_cn") }}</template>
                              </el-input>
                            </div>
                            <div style="margin: 20px">
                              <el-input
                                class="qf_input"
                                :validate-event="false"
                                v-model="ever.fvalue.size_ru"
                                @change="mergeSizeFun(ever.fvalue.size_cn, ever.fvalue.size_ru, ever)"
                                style="max-width: 600px"
                              >
                                <template #prepend> {{ $t("goods_archive.spec_ru") }}</template>
                              </el-input>
                            </div>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>

                    <!-- 1：规格类型 spec_type 2 枚举 -->
                    <!-- 2：颜色 多色都要出现配码组 -->
                    <!--:3：套装格式 package_type 1 - 单尺码 2 - 多尺码 -->

                    <div v-if="props.formConfig.spec_type == 2" class="create_size_box">
                      <div
                        v-if="
                          (props.formConfig.package_type == '2' && ever.fvalue.num_in_packing > 1) ||
                          (ever.fvalue.qifa_color_id == '251' && ever.fvalue.num_in_packing > 1)
                        "
                        :span="6"
                      >
                        <el-popover
                          placement="bottom"
                          width="400"
                          trigger="click"
                          popper-class="own_popper own_popper_big"
                          :visible="ever.popoverVisible"
                          @show="sizeMiniShow(ever, ever.sizeMiniData.dataValue)"
                          @hide="sizeMiniHide(ever, ever.sizeMiniData.dataValue)"
                        >
                          <template #reference>
                            <div
                              class="el-input el-input--default qf_input"
                              @click="ever.popoverVisible = !ever.popoverVisible"
                              v-click-outside="onClickOutside"
                            >
                              <div class="el-input__wrapper">
                                <div class="el-input__inner">
                                  {{ ever.fvalue.size }}
                                  <el-input type="hidden" v-model="ever.fvalue.size" />
                                </div>
                              </div>
                            </div>
                          </template>
                          <div class="size_table_box">
                            <editTableMini
                              v-bind="ever.sizeMiniData"
                              @plusCol="plusCol(ever.sizeMiniData.dataValue)"
                              @delOne="index => delOne(index, ever.sizeMiniData.dataValue, 'minisize', ever)"
                            >
                              <!-- 尺码插槽 -->
                              <template #size="{ scoped }">
                                <div>
                                  <el-select
                                    filterable
                                    :validate-event="false"
                                    value-key="id"
                                    class="qf_select"
                                    :placeholder="$t('merak.placeholder_select')"
                                    v-model="scoped.row.size"
                                    popper-class="own_popper"
                                    :disabled="props.formConfig.package_type == '1' && scoped.index > 0"
                                    @change="
                                      props.formConfig.package_type == '1'
                                        ? one_size_many_colors_fun(ever.sizeMiniData.dataValue, scoped.row.size)
                                        : ''
                                    "
                                  >
                                    <el-option :label="item.label" :value="item.value" v-for="item in sizeArr" :key="item" />
                                  </el-select>
                                </div>
                              </template>
                              <!-- 颜色插槽 -->
                              <template #color="{ scoped }">
                                <div v-if="ever.fvalue.qifa_color_id == '251'">
                                  <el-select
                                    filterable
                                    :validate-event="false"
                                    value-key="id"
                                    class="qf_select"
                                    :placeholder="$t('merak.placeholder_select')"
                                    v-model="scoped.row.color"
                                    popper-class="own_popper"
                                  >
                                    <el-option
                                      :label="item.label"
                                      :value="item.value"
                                      v-for="item in colors.filter(item => item.value != '251')"
                                      :key="item"
                                    />
                                  </el-select>
                                </div>
                                <div v-else style="line-height: 24px">
                                  <span v-if="ever.fvalue.qifa_color_id">
                                    {{ colors.filter(v => v.value == ever.fvalue.qifa_color_id).map(v => v.label)[0] }}
                                  </span>
                                </div>
                              </template>

                              <template #num="{ scoped }">
                                <div>
                                  <el-input
                                    @change="mini_size_all_change(ever.sizeMiniData.dataValue, ever, scoped.row.num)"
                                    v-number
                                    :validate-event="false"
                                    class="editCon"
                                    v-model="scoped.row.num"
                                  ></el-input>
                                </div>
                              </template>
                            </editTableMini>
                          </div>
                          <!-- <div style="display: flex; justify-content: center; margin-top: 6px">
                            {{$t("goods_archive.num_all_mast_be")}}: {{ ever.mini_size_all_num }}
                          </div> -->

                          <div class="error_tip">{{ ever.size_tip }}</div>
                          <div class="sizeMini" style="display: flex; justify-content: center">
                            <el-button type="primary" plain @click="savesize(ever)">{{
                              $t("goods_archive.size_btn_save")
                            }}</el-button>
                          </div>
                        </el-popover>
                      </div>
                      <div v-else>
                        <el-select
                          filterable
                          value-key="id"
                          @change="singleSizeChange(ever.fvalue.size, ever)"
                          class="qf_select"
                          :placeholder="$t('merak.placeholder_select')"
                          v-model="ever.fvalue.size"
                        >
                          <el-option :label="item.label" :value="item.value" v-for="item in sizeArr" :key="item" />
                        </el-select>
                      </div>
                    </div>
                  </template>
                </MerakControl>
              </el-col>
            </el-row>
          </el-form>

          <!-- 带尺码的规格表格 -->
          <div
            class="nooption specTable"
            style="margin-bottom: 15px"
            v-if="ever.own_group_specTable.length > 0 && ever.specTable.columnsValue.length > 0"
          >
            <!-- 手输规格专属标题 -->
            <div v-if="props.formConfig.spec_type == 1" style="margin-bottom: 10px">商品内包装规格</div>

            <editTableMini
              @plusCol="plusCol(ever.specTable.dataValue)"
              @delOne="index => delOne(index, ever.specTable.dataValue)"
              v-bind="ever.specTable"
              :plus="props.formConfig.spec_type == 1 ? true : false"
              :bgClass="props.formConfig.spec_type == 1 ? '' : 'bgColorTable'"
            >
              <template #size="{ scoped }">
                <div>
                  {{ scoped.row.line_size }}
                </div>
              </template>

              <template #ean_barcode="{ scoped }">
                <div>
                  <el-input
                    v-number
                    :validate-event="false"
                    class="editCon"
                    v-model="ever.specTable.dataValue[scoped.index].ean_barcode"
                  ></el-input>
                  <span class="errorTip" v-if="scoped.row.ean_barcode_errInfo">{{ scoped.row.ean_barcode_errInfo }}</span>
                </div>
              </template>

              <template #merge_insole_length="{ scoped }">
                <div>
                  <el-input
                    @input="scoped.row.merge_insole_length = scoped.row.merge_insole_length.replace(/[^0-9\.\_]/g, '')"
                    :validate-event="false"
                    class="editCon"
                    v-model="ever.specTable.dataValue[scoped.index].merge_insole_length"
                  ></el-input>
                  <span class="errorTip" v-if="scoped.row.merge_insole_length_errInfo">{{
                    scoped.row.merge_insole_length_errInfo
                  }}</span>
                </div>
              </template>
            </editTableMini>
          </div>

          <!-- <span @click="get_postdata(specsArr)">提交的数据</span> -->

          <!-- 套件 -->
          <div class="nooption" v-if="ever.suiteTable.columnsValue.length > 0 && props.suite == 1">
            <div style="margin-bottom: 10px">套件内详细信息</div>
            <editTableMini v-bind="ever.suiteTable" :plus="false">
              <template
                v-for="suiteName in ever.suiteTable.columnsValue.filter(v => v.type === 'select').map(v => v.field)"
                #[suiteName]="scope"
              >
                <MerakControl
                  v-model="ever.suiteTable.dataValue[scope.scoped.index][scope.scoped.field]"
                  :query-options="handleQueryOptionsOne"
                  v-bind="ever.suiteTable.columnsValue.find(v => v.field === suiteName)"
                />
              </template>
            </editTableMini>
          </div>

          <!-- 颜色 -->
          <div v-if="props.formConfig.has_color == 0">
            <uploadPic
              :key="`picture_${dateNow}`"
              :ref="(el: refItem) => handleSetInputMap(el, index)"
              v-bind="uploadDataOne"
              v-model="ever.fvalue.imgs"
            >
            </uploadPic>
          </div>
        </div>
      </div>
    </div>

    <div style="text-align: center; padding: 0px">
      <el-button type="primary" @click="addspecs('add')">{{ $t("goods_archive.add_new_sku") }}</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Plus, Edit, Delete, EditPen, CaretTop, CaretBottom } from "@element-plus/icons-vue";

import { ref, reactive, onMounted, getCurrentInstance, nextTick, watch, computed } from "vue";
import MerakControl, { MerakControlProps } from "@/components/MerakControl";

import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";

import { ElButton, ElScrollbar, ElForm, ElMessage, ClickOutside as vClickOutside } from "element-plus";
import I18n from "@/languages/index";
import basicTableSum from "@/components/MerakEditTable/components/basicTable/moreEdit.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { OptionType, getOptions, validsku } from "@/api/modules/goodsArchive/addGoodsArchive";
import { useRouter, useRoute } from "vue-router";
import editTableMini from "@/components/MerakEditTable/components/editTableMini/index.vue";
import uploadPic from "@/components/uploadFileMerak/picUpload.vue";
import { number } from "mathjs";
const $t = I18n.global.t;
const router = useRouter();
const route = useRoute();

const props = withDefaults(
  defineProps<{
    id: string | number;
    span: number;
    sizeStandard?: string | number;
    formConfig: Record<string, any>; //表单的配置项
    specsInitial: Record<string, any>; //规格信息的所有数据
    spmColors?: Array<OptionType>; //商家颜色
    sku_before?: Record<string, any>; //spu
    suite: string | number;
  }>(),
  {
    spmColors: () => []
  }
);

const emit = defineEmits<{
  change: [params: any];
}>();

// 处理动态上传图片组件
const inputRefMap = ref({});
const dateNow = ref();
const uploadDataOne = reactive({
  path: "/goods-archive/product-edit/upload-thumbnails"
});
const handleSetInputMap = (el: refItem, item: number) => {
  if (el) {
    inputRefMap.value[`imgRef_${item}`] = el;
  }
};

const Items: MerakControlProps[] = ref([]); //动态item组
const sku_before = ref(""); //型号，货号前缀
const specsArr = ref([
  {
    fvalue: {
      sku: "",
      num_in_packing: 1,
      size_ru: "",
      size_cn: "",
      imgs: []
    },
    mini_size_all_num: 1,
    sku_error: [],
    Items: [],
    own_group_specTable: [],
    popoverVisible: false,
    specTable: {
      columnsValue: [],
      dataValue: []
    },
    suiteTable: {
      columnsValue: [],
      dataValue: []
    },
    sizeMiniData: {
      columnsValue: [
        { field: "size", title: $t("goods_archive.size_table_size") },
        { field: "num", title: $t("goods_archive.size_table_num") + " (1)" },
        { field: "color", title: $t("goods_archive.size_table_color") }
      ],
      dataValue: [
        {
          size: "",
          color: "",
          num: 1
        }
      ]
    }
  }
]);
const specsArrOld = ref([]);

specsArrOld.value = JSON.parse(JSON.stringify(specsArr.value));
const colors = ref([]); //颜色下拉options
const sizeArr = ref([]); //尺码下拉options

// 修改码质 影响尺码的下拉数据
watch(
  () => props.sizeStandard,
  val => {
    if (props.sizeStandard) {
      console.log(sizeStandardMap.value[props.sizeStandard]);

      sizeArr.value = sizeStandardMap.value[props.sizeStandard];

      specsArr.value.forEach(item => {
        if (item.fvalue.size) {
          item.fvalue.size = "";
        }

        if (item.specTable.dataValue.length > 0) {
          var one_line = item.specTable.dataValue[0];
          for (var i in one_line) {
            one_line[i] = "";
          }
          item.specTable.dataValue = [one_line];
        }
        item.sizeMiniData.dataValue = [
          {
            size: "",
            color: "",
            num: 1
          }
        ];
      });
    }
  }
);
watch(
  () => props.spmColors,
  val => {
    if (props.spmColors) {
      specsArr.value.forEach(ever => {
        console.log(ever.Items);
        ever.Items.filter(line => {
          if (line.field == "supplier_color_id") {
            line["disabled"] = false;
          }
        });
      });
    }
  }
);

const spmColors = ref([]);
const sizeStandardMap = ref([]);
// 初始化清空操作
const initFun = () => {
  dateNow.value = Date.now();
  sku_before.value = props.sku_before;
  specsArr.value[0].Items = props.specsInitial.info;
  specsArr.value[0].own_group_specTable = props.specsInitial.specTable;
  specsArr.value[0].suiteTable.columnsValue = props.specsInitial.suiteTable;
  specsArr.value[0].specTable.columnsValue = props.specsInitial.specTable;
  sizeStandardMap.value = props.specsInitial.sizeStandardMap;

  // 手输入规格的规格子表格单独处理
  if (specsArr.value[0].specTable.columnsValue.length > 0) {
    var linenum = 1;

    for (let index = 0; index < linenum; index++) {
      var _dataValue_obj = {};
      for (let index = 0; index < specsArr.value[0].specTable.columnsValue.length; index++) {
        var cur = specsArr.value[0].specTable.columnsValue[index];
        _dataValue_obj[cur.field] = "";
      }
      specsArr.value[0].specTable.dataValue.push(_dataValue_obj);
    }
  }
  if (props.formConfig.spec_type == 1 || props.id == "13") {
    specsArr.value[0].own_group_specTable = [];
  }

  // 套件信息行数是固定的  商品类型毛巾行数是3，床品是5
  if (specsArr.value[0].suiteTable.columnsValue.length > 0) {
    var linenum = 0;
    console.log(props.id);
    if (props.id == 3) {
      linenum = 3;
    }
    if (props.id == 9) {
      linenum = 5;
    }

    for (let index = 0; index < linenum; index++) {
      var _dataValue_obj = {};
      for (let index = 0; index < specsArr.value[0].suiteTable.columnsValue.length; index++) {
        var cur = specsArr.value[0].suiteTable.columnsValue[index];
        _dataValue_obj[cur.field] = "";
      }
      specsArr.value[0].suiteTable.dataValue.push(_dataValue_obj);
    }
  }

  var Items2 = JSON.parse(JSON.stringify(specsArr.value[0].Items));
  for (let index = 0; index < Items2.length; index++) {
    const element = Items2[index];
    if (element.field == "num_in_packing") {
      element["required"] = 1;
    }
    if (element.field == "size") {
      element["required"] = 1;
    }
    if (element.field == "supplier_color_id") {
      element["disabled"] = true;
    }
    if (element.field == "qifa_color_id") {
      specsArr.value[0].Items;
      colors.value = element.options;
    }
    if (element.field == "volume" && props.id == 1) {
      element["custom"] = 1;
    }
    if (element.field == "size" && element.options?.length > 0) {
      sizeArr.value = element.options;
    }

    // 海关编码(俄) 海关编码(中)最大10位数字
    if (element.field == "hs_code" || element.field == "hs_code_cn") {
      element["maxlength"] = 10;
    }
  }

  specsArr.value[0].Items = Items2;

  console.log(specsArr.value);
};

// 初始化选项
onMounted(() => {
  console.log(props.specsInitial);
  initFun();
});
// 修改体积 鞋类商品的体积0.29
const changeVolume = (volume, ever) => {
  if (props.id == "1") {
    volume = parseFloat(volume);
    if (volume > 0.29) {
      ever.fvalue.volume = 0.29;
    }
  }
};

// 新增规格
const addspecs = (type, ever) => {
  var specsArr2 = JSON.parse(JSON.stringify(specsArr.value));
  var _obj = {};
  if (type == "add") {
    _obj = specsArr2[0];
    console.log(_obj);

    for (var i in _obj.fvalue) {
      if (i != "sku") {
        _obj.fvalue[i] = "";
      }
    }
    if (_obj.specTable.dataValue.length > 0) {
      var one_line = _obj.specTable.dataValue[0];
      for (var i in one_line) {
        one_line[i] = "";
      }
      _obj.specTable.dataValue = [one_line];
      console.log(_obj.specTable.dataValue);
    }

    if (_obj.suiteTable.dataValue.length > 0) {
      var one_line = _obj.suiteTable.dataValue[0];
      for (var i in one_line) {
        one_line[i] = "";
      }
      _obj.suiteTable.dataValue = [one_line];
    }
  }
  if (type == "copy") {
    _obj = JSON.parse(JSON.stringify(ever));
    _obj.fvalue.qifa_color_id = "";
    _obj.fvalue.supplier_color_id = "";
  }
  _obj.sku_error = [];
  _obj.imgs = [];
  var prev_sku = _obj.fvalue.sku;
  prev_sku = prev_sku.substr(-1);

  prev_sku = Number(prev_sku);
  if (!prev_sku) {
    prev_sku = 0;
  }

  prev_sku = prev_sku + 1;
  _obj.fvalue.sku = _obj.fvalue.sku.slice(0, -1) + prev_sku;
  console.log(_obj);
  specsArr.value.push(_obj);
};

// 删除规格
const delspecs = index => {
  specsArr.value.splice(index, 1);
};

// 遍历颜色
const colorArr = ref([]);

const colorfun = (ever, index) => {
  console.log(ever);
  no_size_more_colors(ever, index);
  // 多色 修改颜色，处理规格子表格
  if (ever.fvalue.qifa_color_id == "251") {
    if (ever.fvalue.num_in_packing > 1) {
      // 手输入规格的规格子表格单独处理
      ever.specTable.dataValue = [];
      if (ever.specTable.columnsValue.length > 0) {
        var linenum = 1;

        for (let index = 0; index < linenum; index++) {
          var _dataValue_obj = {};
          for (let index = 0; index < ever.specTable.columnsValue.length; index++) {
            var cur = ever.specTable.columnsValue[index];
            _dataValue_obj[cur.field] = "";
          }
          ever.specTable.dataValue.push(_dataValue_obj);
        }
      }
      ever.fvalue.size = "";
      ever.sizeMiniData.dataValue = [{ size: "", color: "", num: 1 }];
    }
  } else {
    if (ever.sizeMiniData.dataValue.length > 0) {
      ever.sizeMiniData.dataValue.forEach(element => {
        element.color = ever.fvalue.qifa_color_id;
      });
    }
  }

  // 修改颜色，处理下方传图的块，颜色重复下方上传图片颜色，只出现一次
  var specsArr2 = JSON.parse(JSON.stringify(specsArr.value));
  console.log(specsArr2);
  var color_arr = [];
  for (let index = 0; index < specsArr2.length; index++) {
    const element = specsArr2[index];

    console.log(element.fvalue.qifa_color_id);
    if (color_arr.includes(element.fvalue.qifa_color_id)) {
    } else {
      if (element.fvalue.qifa_color_id) {
        color_arr.push(element.fvalue.qifa_color_id);
      }
    }
  }
  colorArr.value = color_arr;

  var colorsall = [];
  for (var i in color_arr) {
    var new_color = {};
    new_color["value"] = color_arr[i];
    for (let index = 0; index < colors.value.length; index++) {
      const element = colors.value[index];
      if (element.value == color_arr[i]) {
        new_color["label"] = element.label;
        new_color["color_image"] = element.color_image;
      }
    }

    colorsall.push(new_color);
  }

  emit("change", colorsall);

  console.log(colorsall);
};

const popoverRef = ref();
const popoverVisible = ref(false);
const change_popover_key = ref(false);
const change_popover_item = () => {
  change_popover_key.value = true;
  console.log(change_popover_key.value);
};

const options = [
  {
    value: "Option1",
    label: "Option1"
  },
  {
    value: "Option2",
    label: "Option2"
  },
  {
    value: "Option3",
    label: "Option3"
  },
  {
    value: "Option4",
    label: "Option4"
  },
  {
    value: "Option5",
    label: "Option5"
  }
];
const hasParentClass = (element, className) => {
  // 检查元素是否为null或者undefined
  if (!element) return false;

  // 获取父级元素
  var parent = element.parentElement;

  // 如果父级元素存在，则检查它的类名
  while (parent) {
    if (parent.classList.contains(className)) {
      return true; // 找到匹配的类，返回true
    }
    // 继续向上查找父级元素
    parent = parent.parentElement;
  }

  return false; // 没有找到匹配的类，返回false
};

// 点击规格子表格，收起
const onClickOutside = (e: any) => {
  var hasParentWithClass = hasParentClass(e.target, "own_popper"); // 检查父级元素是否有'myParentClass'类
  console.log(hasParentWithClass);
  if (hasParentWithClass) {
  } else {
    for (let index = 0; index < specsArr.value.length; index++) {
      const element = specsArr.value[index];
      element.popoverVisible = false;
      element.size_tip = "";
    }
  }
};

const num_input = ref(1);

// 修改外包装内数量
const change_num_inpaking = (ever, num_input, index: number) => {
  num_input = parseInt(num_input);
  console.log(num_input);
  if (num_input < 1) {
    console.log("小于");
    ever.fvalue.num_in_packing = 1;
  }
 
  // 手输入规格的规格子表格单独处理
  var message = $t("goods_archive.please_select_size");
  if (props.formConfig.spec_type == 2) {
    no_size_more_colors(ever, index);
    ever.specTable.dataValue = [];
    if (ever.specTable.columnsValue.length > 0) {
      var linenum = 1;

      for (let index = 0; index < linenum; index++) {
        var _dataValue_obj = {};
        for (let index = 0; index < ever.specTable.columnsValue.length; index++) {
          var cur = ever.specTable.columnsValue[index];
          _dataValue_obj[cur.field] = "";
        }
        ever.specTable.dataValue.push(_dataValue_obj);
      }
    }

    if (props.formConfig.package_type == "2" && ever.fvalue.num_in_packing > 1) {
      message = $t("goods_archive.please_input_size");
    }
    ever.Items.filter(item => {
      if (item.field == "size") {
        item["message"] = message;
      }
    });
    console.log(ever);
  }
  // 文本格式且外包装数量小于2，置空
  if ((props.formConfig.spec_type == 1 && num_input < 2) || (props.id == "13" && num_input < 2)) {
    ever.own_group_specTable = [];
  } else {
    ever.own_group_specTable = ever.specTable.dataValue;
  }

  if (props.formConfig.package_type == "2" && ever.fvalue.size != "") {
    refs[index].resetFields(["size"]);
  }
  ever.sizeMiniData.dataValue = [{ size: "", color: "", num: 1 }];
  if (ever.fvalue.qifa_color_id == "251" && num_input < 2) {
    ever.fvalue.qifa_color_id = "";
  }
  mini_size_all_change(ever.sizeMiniData.dataValue, ever);
};

// 修改配码表
const size_tip = ref("");
const findsizetext = id => {
  var curtext = "";
  for (let index = 0; index < sizeArr.value.length; index++) {
    const element = sizeArr.value[index];
    if (element.value == id) {
      curtext = element.label;
    }
  }
  return curtext;
};

const findcolortext = id => {
  var curtext = "";
  console.log(colors);
  for (let index = 0; index < colors.value.length; index++) {
    const element = colors.value[index];
    if (element.value == id) {
      curtext = element.label;
    }
  }
  return curtext;
};

// 后台发送接口验证sku/唯一
const check_sku = async (ever, sku, index) => {
  var sku_before = "";
  if (!props.sku_before) {
    sku_before = "";
    sku = sku;
  } else {
    if (sku == "") {
      sku = props.sku_before;
    } else {
      sku = props.sku_before + "-" + sku;
    }
  }

  var postsku = await validsku(sku).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      del_spec_error(ever, index, "one");
      return true;
    } else {
      add_spec_error(ever, index, "one");
      return false;
    }
  });

  return Promise.resolve(postsku);
};

// 处理获取选项事件
const handleQueryOptions = async (field: string) => {
  return new Promise<MerakControlOption[]>(resolve => {
    getOptions(props.id, field, props.suite).then(({ code, data }) => {
      if (code == ResultEnum.SUCCESS) {
        resolve(data);
      }
    });
  });
};

// 处理获取选项事件
const handleQueryOptionsOne = async (field: string) => {
  return new Promise<MerakControlOption[]>(resolve => {
    const suite = 0;
    getOptions(props.id, field, suite).then(({ code, data }) => {
      if (field === "cc_goods_name") {
        console.log("cc_goods_name", suite);
      }
      ("");
      if (code == ResultEnum.SUCCESS) {
        resolve(data);
      }
    });
  });
};

// 数字排序
const sortNum = (a, b) => {
  return a - b;
};
// 判断是否是数字
const IsNum = s => {
  var num = /^[0-9]+.?[0-9]*$/; //判断正整数 /^[1-9]+[0-9]*]*$/

  if (!num.test(s)) {
    return false;
  }
  return true;
};

// 规格子表格中数量修改，算总计
const mini_size_all_change = (dataValue, ever, num) => {
  console.log(dataValue);
  var numall = 0;
  for (let index = 0; index < dataValue.length; index++) {
    const element = dataValue[index];

    var cur_num = element.num;
    if (cur_num) {
      cur_num = parseInt(cur_num);
      if (cur_num == 0 || cur_num == "0") {
        element.num = 1;
        cur_num = 1;
      }
    }

    if (cur_num > 0) {
      numall += cur_num;
    }
  }
  console.log(numall);
  ever.mini_size_all_num = numall;

  var numtit = $t("goods_archive.size_table_num") + " (" + numall + ")";
  ever.sizeMiniData.columnsValue[1] = { field: "num", title: numtit };
};

// 规格子表格，点击完成验证
// 1:尺码+数量 不能重复
// 2:数量合计必须等于外包装内数量
// 3:影响规格表格
const savesize = ever => {
  console.log(ever);
  var num_in_packing = ever.fvalue.num_in_packing;
  num_in_packing = Number(num_in_packing);
  var dataValue = ever.sizeMiniData.dataValue;

  var numall = 0;
  var size_text = "";
  var num_text = "";
  var size_color_num = [];
  var confrim_size_arr = [];
  ever.size_tip = "";

  // 单色自动填补配码表的颜色列值
  for (let index = 0; index < dataValue.length; index++) {
    const element = dataValue[index];
    var cur_num = parseInt(element.num);
    if (cur_num > 0) {
      numall += cur_num;
      console.log(element.size + element.color + "");
      console.log(element);

      if (ever.fvalue.qifa_color_id != "251") {
        element.color = ever.fvalue.qifa_color_id;
        if (element.size == "" || !!element.num == "") {
          ever.size_tip = $t("goods_archive.pleas_complete_the_code_form");
          ever.fvalue.size = "";
          ever.fvalue.more_color = "";
          return false;
        }
      } else {
        if (props.formConfig.has_size == 0) {
          if (!!element.num == "" || !!element.color == "") {
            ever.size_tip = $t("goods_archive.pleas_complete_the_code_form");
            ever.fvalue.size = "";
            ever.fvalue.more_color = "";
            return false;
          }
        } else {
          if (element.size == "" || !!element.num == "" || !!element.color == "") {
            ever.size_tip = $t("goods_archive.pleas_complete_the_code_form");
            ever.fvalue.size = "";
            ever.fvalue.more_color = "";
            return false;
          }
        }
      }

      if (size_color_num.includes("" + element.size + element.color)) {
        ever.size_tip = $t("goods_archive.value_cannot_repeated");
        ever.fvalue.size = "";
        ever.fvalue.more_color = "";
        return false;
      } else {
        size_color_num.push("" + element.size + element.color);
      }
    } else {
      ever.size_tip = $t("goods_archive.pleas_complete_the_code_form");
      ever.fvalue.size = "";
      ever.fvalue.more_color = "";
      return false;
    }
  }

  if (props.formConfig.has_size != 0) {
    const map = new Map();
    let sizeArr = new Array();
    for (var i = 0; i < dataValue.length; i++) {
      if (dataValue[i].size && dataValue[i].num) {
        if (map.has(dataValue[i].size)) {
          var num_temp = map.get(dataValue[i].size);
          num_temp = parseInt(num_temp);
          map.set(dataValue[i].size, num_temp + parseInt(dataValue[i].num));
        } else {
          sizeArr.push(dataValue[i].size);
          map.set(dataValue[i].size, dataValue[i].num);
        }
      }
    }

    console.log(sizeArr);
    console.log(map);
    console.log("-------------------------");

    let sortArr = sizeArr;
    let str2 = "";
    console.log(sortArr);
    for (var i = 0; i < sortArr.length; i++) {
      console.log(sortArr[i] + "---" + map.get(sortArr[i]));

      var confrim_size_arr_obj = {};
      confrim_size_arr_obj["label"] = findsizetext(sortArr[i]);
      confrim_size_arr_obj["value"] = sortArr[i];
      confrim_size_arr.push(confrim_size_arr_obj);
      size_text += findsizetext(sortArr[i]) + "-";
      num_text += map.get(sortArr[i]) + "-";
    }
    console.log(dataValue);

    // const newarr = dataValue.reduce((prev, next) => {
    //   const index = prev.findIndex(item => item.size === next.size)
    //   if (index !== -1) {
    //     prev[index] = prev[index].num + parseInt(next.num)
    //   } else {
    //     prev.push({
    //       size: next.size,
    //       num: parseInt(next.num)
    //     })
    //   }
    //   return prev
    //   // prev[`${next.size}`] = parseInt((prev?.[`${next.size}`] ?? 0)) + parseInt(next.num)
    //   // return {
    //   //   'size':prev,
    //   //   'num':
    //   // }
    // },
    //   []
    // );

    // console.log(newarr)
  } else {
    dataValue.forEach(tr => {
      console.log(tr.color);
      console.log(findcolortext(tr.color));
      size_text += findcolortext(tr.color) + "-";
      num_text += tr.num + "-";
    });
  }

  if (numall == num_in_packing) {
    ever.size_tip = "";
    var lastsize_text = size_text.slice(0, -1) + "(" + num_text.slice(0, -1) + ")";

    // 全部通过走啦
    console.log(lastsize_text);

    ever.fvalue.size = lastsize_text;
    ever.fvalue.more_color = lastsize_text;
    ever.confrim_size_arr = confrim_size_arr;
    console.log(confrim_size_arr);

    var pushitem = ever.specTable.columnsValue;
    var specTable_dataValue = [];
    console.log(confrim_size_arr);
    if (pushitem.length > 0) {
      for (let index = 0; index < confrim_size_arr.length; index++) {
        var _obj = {};
        const element = confrim_size_arr[index];
        console.log(element);
        _obj["size"] = element.value;
        _obj["line_size"] = element.label;
        for (let index = 0; index < pushitem.length; index++) {
          const line = pushitem[index];
          if (line.field != "size") {
            _obj[line.field] = "";
          }
        }
        console.log(_obj);
        specTable_dataValue.push(_obj);
      }
    }

    console.log(specTable_dataValue);

    ever.specTable = {
      columnsValue: pushitem,
      dataValue: specTable_dataValue
    };

    ever.popoverVisible = false;
    console.log("尺码表格点击完成，切换了小表格数据");
    if_click_save.value = 1;
  } else {
    ever.size_tip = $t("goods_archive.num_all_mast_be") + num_in_packing;
    ever.fvalue.size = "";
    ever.fvalue.more_color = "";
  }
};
// 没有尺码，但可以选多色
const no_size_more_colors = (ever, index) => {
  ever.fvalue.more_color = "";
  for (let index = 0; index < ever.Items.length; index++) {
    const element = ever.Items[index];
    if (element.field == "more_color") {
      ever.Items.splice(index, 1);
    }
  }
  console.log("进入多色信息生成");
  refs[index].resetFields(["size"]);
  refs[index].resetFields(["more_color"]);
  if (
    props.formConfig.has_size == 0 &&
    props.formConfig.has_color == 1 &&
    ever.fvalue.qifa_color_id == "251" &&
    ever.fvalue.num_in_packing > 1
  ) {
    var more_color = {
      field: "more_color",
      required: 1,
      title: "多色信息",
      type: "input",
      custom: 1
    };
    console.log(ever.Items);
    ever.Items.splice(2, 0, more_color);
    console.log("清除报错");
    refs[index].resetFields(["size"]);
    refs[index].resetFields(["supplier_sku"]);
    refs[index].resetFields(["more_color"]);
  }
};
// 单尺码修改
const singleSizeChange = (sizeid, ever) => {
  // 只有规格子表格有值才操作，把规格子表格的左侧尺码填写上
  if (ever.specTable.columnsValue.length > 0) {
    ever.specTable.dataValue[0].size = sizeid;
    sizeArr.value.filter(function (item) {
      if (item.value == sizeid) {
        ever.specTable.dataValue[0].line_size = item.label;
      }
      return false;
    });
  }
};

// 操作小表格的增加 尺码小表格增加的时候
const plusCol = (data, type) => {
  var _obj = JSON.parse(JSON.stringify(data[0]));
  if (props.formConfig.package_type == "1") {
    one_size_many_colors.value = 1;
  }
  var one_line_size = "";
  if ((type = "minisize" && one_size_many_colors.value == 1)) {
    one_line_size = _obj.size;
  }
  for (var i in _obj) {
    _obj[i] = "";
  }
  if ((type = "minisize" && one_size_many_colors.value == 1)) {
    _obj.size = one_line_size;
  }

  data.push(_obj);
};

// 操作小表格的删除
const delOne = (index, ever, type, everdata) => {
  if (ever.length > 1) {
    ever.splice(index, 1);
    if (type == "minisize") {
      mini_size_all_change(ever, everdata);
    }
  }
};

const temp_minisize = ref();
const if_click_save = ref(0);
// 配码表格显示
const sizeMiniShow = ever => {
  console.log(ever);
  temp_minisize.value = JSON.parse(JSON.stringify(ever.sizeMiniData));
  if_click_save.value = 0;
  console.log(temp_minisize.value);
};
// 配码表格隐藏
const sizeMiniHide = ever => {
  console.log(ever);
  console.log(if_click_save.value);
  if (if_click_save.value == 0) {
    console.log("不是点击了完成按钮的收起");
    console.log(temp_minisize.value);
    if (!(JSON.stringify(ever.sizeMiniData) == JSON.stringify(temp_minisize.value))) {
      ever.sizeMiniData = temp_minisize.value;
      console.log("发生了变化");
    }
  }
};

const guige1 = ref("");
const guige2 = ref("");

const guige_all = ref("");

// const visiblechange = (type) => {
//   console.log(type)
//   if (type == false) {
//     guige_all.value = guige1.value + '-' + guige2.value
//   }

// }

const sku_error_tips = {
  one: $t("goods_archive.tip_system_sku_is_has"), //系统货号在系统中已存在
  two: $t("goods_archive.tip_system_sku_is_only"), //系统货号」需要在型号下保持唯一
  three: $t("goods_archive.tip_no_some_color_size"), //系统货号颜色、尺码信息不能相同
  four: $t("goods_archive.tip_color_qifacolor"), //「企发颜色/商家颜色」二者选一必填
  five: $t("goods_archive.tip_spec_table"), //规格表格输入有误
  six: "填写完整部件信息(儿童游乐设备货号、拆分图序号、部件数量)", //填写完整部件信息(儿童游乐设备货号、拆分图序号、部件数量)
  seven: "只能存在一条多色",
  eight:'商品外包装规格不能重复'
};
// 规格整块添加报错
const add_spec_error = (element, index, errorkey) => {
  specsArr.value[index].sku_error.push(errorkey);
  console.log(element.sku_error);
  element.sku_error = specsArr.value[index].sku_error;
  element.evergo = 0;
};
// 规格整块删除报错
const del_spec_error = (element, index, errorkey) => {
  specsArr.value[index].sku_error = specsArr.value[index].sku_error?.filter(function (item) {
    return item != errorkey;
  });

  element.sku_error = element.sku_error?.filter(function (item) {
    return item != errorkey;
  });
};

//合并规格
const mergeSizeFun = (cn, ru, ever) => {
  if (!!cn || !!ru) {
    ever.fvalue.size = cn + "-" + ru;
  } else {
    ever.fvalue.size = "";
  }
};
const one_size_many_colors = ref(0);
// 插槽单尺码修改
const one_size_many_colors_fun = (data, cursize) => {
  console.log("单尺码多色修改");
  data.forEach(key => {
    console.log(key);
    key.size = cursize;
  });
  one_size_many_colors.value = 1;
};

// 规格整块验证
const specVerify = async (element, index, cc_model) => {
  element["evergo"] = 1;
  for (var i in sku_error_tips) {
    del_spec_error(element, index, i);
  }
  const flag = await check_sku(element, element.fvalue.sku, index);
  if (!element.fvalue?.sku) {
    element.fvalue.sku = "";
  }

  // 商品类型是 儿童游乐设备部件， 儿童游乐设备货号 拆分图序号 部件数量三项填写一项就都需要必填
  if (props.id == "24") {
    var unitarr = ["combination_sku", "split_sequence", "part_quantity"];
    if (!!element.fvalue.combination_sku || !!element.fvalue.split_sequence || !!element.fvalue.part_quantity) {
      console.log("验证部件youkong ");
      unitarr.forEach(key => {
        if (!element.fvalue[key]) {
          del_spec_error(element, index, "six");
          add_spec_error(element, index, "six");
        }
      });
    }
  }
  // element["error"] = 'sdfsdfsdfsdaf';

  if (check_sku_only.includes(element.fvalue.sku)) {
    add_spec_error(element, index, "two");
  } else {
    check_sku_only.push(element.fvalue.sku);
  }

  // var only_info =
  //   "" + element.fvalue.qifa_color_id + element.fvalue.num_in_packing + element.fvalue.size + element.fvalue.supplier_color_id;
  // if (check_only.includes(only_info)) {
  //   add_spec_error(element, index, "three");
  // } else {
  //   check_only.push(only_info);
  // }

  // props.tableData.forEach(element => {
  //   var only_qifa_info = "" + element.qifa_color_id + element.num_in_packing + element.size;
  //   qifa_color_only.push(only_qifa_info);

  //   var only_supplier_info = "" + element.num_in_packing + element.size + element.supplier_color_id;
  //   supplier_color_only.push(only_supplier_info);
  // });

  var cur_qifa_only_info = "" + element.fvalue.qifa_color_id + element.fvalue.num_in_packing + element.fvalue.size;
  var cur_supplier_only_info = "" + element.fvalue.num_in_packing + element.fvalue.size + element.fvalue.supplier_color_id;

  if (qifa_color_only.includes(cur_qifa_only_info)) {
    add_spec_error(element, index, "three");
  } else {
    qifa_color_only.push(cur_qifa_only_info);
  }

  console.log(supplier_color_only);
  if (supplier_color_only.includes(cur_supplier_only_info) && !!element.fvalue.supplier_color_id) {
    del_spec_error(element, index, "three");
    add_spec_error(element, index, "three");
  } else {
    supplier_color_only.push(cur_supplier_only_info);
  }

  if (is_has_more_clors.includes("251") || (is_has_more_clors.includes(251) && element.fvalue.qifa_color_id == "251")) {
    add_spec_error(element, index, "seven");
  } else {
    is_has_more_clors.push(element.fvalue.qifa_color_id);
  }


  // 商品外包装规格不能重复 手输入规格
  if (props.formConfig.spec_type == 1) {

    if (size_cn_only.includes(element.fvalue.size_cn)) {
        add_spec_error(element, index, "eight");
      } else {
        size_cn_only.push(element.fvalue.size_cn);
      }

      if (size_ru_only.includes(element.fvalue.size_ru)) {
        del_spec_error(element, index, "eight");
        add_spec_error(element, index, "eight");
      } else {
        size_ru_only.push(element.fvalue.size_ru);
      }
      
  }











  if (props.formConfig.has_color == 1) {
    if (element.fvalue.qifa_color_id || element.fvalue.supplier_color_id) {
    } else {
      add_spec_error(element, index, "four");
    }
  }

  // 鞋 清关选--款式--鞋垫内长必填
  if (props.id == "1" && cc_model == "5511") {
    const post_specTable = specsArr.value[index].specTable.dataValue;
    for (let index = 0; index < post_specTable.length; index++) {
      const spec_table_ever = post_specTable[index];

      console.log(!!spec_table_ever.merge_insole_length);
      if (!!spec_table_ever.merge_insole_length) {
        spec_table_ever.merge_insole_length_errInfo = "";
      } else {
        spec_table_ever.merge_insole_length_errInfo = $t("merak.tip_mast_input");
      }
    }
    for (let i = 0; i < post_specTable.length; i++) {
      const spec_table_ever = post_specTable[i];
      if (spec_table_ever.merge_insole_length_errInfo) {
        del_spec_error(element, index, "five");
        add_spec_error(element, index, "five");
      }
    }
  }

  // 规格是手动输入

  const post_specTable = specsArr.value[index].specTable.dataValue;
  if (element.fvalue.num_in_packing > 1) {
    // 循环遍历中，规格列中当前列只要存在值，当前列就必须都填写
    var need_verify_key = []; //需要验证必填的列字段key的数组
    post_specTable.forEach((value, key) => {
      console.log(value, key);
      for (var i in value) {
        console.log(i);
        if (i.includes("_errInfo")) {
          value[i] = "";
        }
        if (!!value[i] && need_verify_key.includes(i) == false && i != "size" && i != "line_size") {
          need_verify_key.push(i);
        }
      }
    });
    console.log(need_verify_key);
  }

  if (element.fvalue.num_in_packing > 1) {
    var spec_size_cn_arr = [];
    var spec_size_ru_arr = [];
    var spec_num_arr = 0;
    var spec_ean_barcode_arr = [];
    for (let index = 0; index < post_specTable.length; index++) {
      const spec_table_ever = post_specTable[index];

      if (props.formConfig.spec_type == 1) {
        // 商品规格(中文)不能重复
        if (spec_table_ever.size_cn) {
          spec_table_ever.size_cn_errInfo = "";
          if (spec_size_cn_arr.includes(spec_table_ever.size_cn) || spec_table_ever.size_cn == element.fvalue.size_cn) {
            spec_table_ever.size_cn_errInfo = $t("merak.tip_mast_some");
          } else {
            spec_size_cn_arr.push(spec_table_ever.size_cn);
            spec_table_ever.size_cn_errInfo = "";
          }
        } else {
          spec_table_ever.size_cn_errInfo = $t("merak.tip_mast_input");
        }

        // 商品规格(俄文)
        if (spec_table_ever.size_ru) {
          spec_table_ever.size_ru_errInfo = "";
          if (spec_size_ru_arr.includes(spec_table_ever.size_ru) || spec_table_ever.size_cn == element.fvalue.size_ru) {
            spec_table_ever.size_ru_errInfo = $t("merak.tip_mast_some");
          } else {
            spec_size_ru_arr.push(spec_table_ever.size_ru);
            spec_table_ever.size_ru_errInfo = "";
          }
        } else {
          spec_table_ever.size_ru_errInfo = $t("merak.tip_mast_input");
        }

        // 数量
        if (spec_table_ever.num) {
          spec_table_ever.num_errInfo = "";
          console.log(spec_table_ever.num);
          if (spec_table_ever.num == "0" || spec_table_ever.num == 0) {
            spec_table_ever.num_errInfo = "必须大于1";
          } else {
            spec_num_arr += parseInt(spec_table_ever.num);
          }
        } else {
          spec_table_ever.num_errInfo = $t("merak.tip_mast_input");
        }

        // 条形码
        if (spec_table_ever.ean_barcode) {
          spec_table_ever.ean_barcode_errInfo = "";
          var cur_ean_barcode = spec_table_ever.ean_barcode;
          if (cur_ean_barcode.length == 14 || cur_ean_barcode.length == 13) {
            spec_table_ever.ean_barcode_errInfo = "";
          } else {
            spec_table_ever.ean_barcode_errInfo = $t("goods_archive.tip_barcode_length");
          }
        } else {
          spec_table_ever.ean_barcode_errInfo = $t("merak.tip_mast_input");
        }
      }

      // 验证带尺码的规格表格，当前列有一项填写，整列都需要填写

      if (need_verify_key.length > 0) {
        need_verify_key.forEach(need_key => {
          console.log(need_key);
          if (!need_key.includes("_errInfo")) {
            if (spec_table_ever[need_key]) {
            } else {
              spec_table_ever[need_key + "_errInfo"] = $t("merak.tip_mast_input");
            }
          }
        });
      }
    }

    if (props.formConfig.spec_type == 1) {
      // 商品数量必须等于外包装内数量
      var len = post_specTable.length;
      var cur_num_in_packing = element.fvalue.num_in_packing;
      if (cur_num_in_packing == spec_num_arr) {
        if (post_specTable[len - 1].num > 0) {
          post_specTable[len - 1].num_errInfo = "";
        }
      } else {
        post_specTable[len - 1].num_errInfo = $t("goods_archive.num_all_mast_be") + cur_num_in_packing;
      }
    }

    console.log(post_specTable);
    for (let i = 0; i < post_specTable.length; i++) {
      var spec_td = 1;
      const spec_table_ever = post_specTable[i];
      for (var key in spec_table_ever) {
        if (key.includes("_errInfo")) {
          if (spec_table_ever[key]) {
            spec_td = 0;
          }
        }
      }

      if (spec_td == 0) {
        del_spec_error(element, index, "five");
        add_spec_error(element, index, "five");
        return false;
      }
    }
  }
  return Promise.resolve();
};

// 清楚规格表格报错
const clear_noval_line = data => {
  data = data.filter(item => {
    var all_null = true;
    for (var i in item) {
      if (i == "size" || i == "line_size") {
      } else {
        if (item[i] != "") {
          all_null = false;
        }
      }
    }
    if (all_null == false) {
      return item;
    }
  });
  console.log(data);
  return data;
};

var check_sku_only = [];
var qifa_color_only = [];
var size_cn_only=[];
var size_ru_only=[];
var is_has_more_clors = [];
var supplier_color_only = [];
const get_postdata = async cc_model => {
  console.log(cc_model);
  var allArr = JSON.parse(JSON.stringify(specsArr.value));
  console.log(allArr);

  var delobjs = ["Items", "confrim_size_arr", "own_group_specTable", "popoverVisible", "sizeMiniData"];

  qifa_color_only = [];
  supplier_color_only = [];
  check_sku_only = [];
  is_has_more_clors = [];
  size_cn_only=[];
  size_ru_only=[];

  var letgo = 1;
  for (let index = 0; index < allArr.length; index++) {
    const element = allArr[index];

    await specVerify(element, index, cc_model);

    element["form"] = element.fvalue;

    for (var i in element.fvalue) {
      if (!!element.fvalue[i]) {
        element[i] = element.fvalue[i];
      }
    }
    delete element.form;

    element["specTable"] = clear_noval_line(element.specTable.dataValue ?? []);

    element["colorsArr"] = element.sizeMiniData.dataValue;

    if (props.formConfig.package_type == "1" && element.num_in_packing > 1 && element.qifa_color_id != "251") {
      element["colorsArr"] = [{ size: element.size, color: "", num: element.num_in_packing }];
    }
    if (props.formConfig.package_type == "0" && element.num_in_packing > 1 && element.qifa_color_id != "251") {
      element["colorsArr"] = [{ size: "", color: element.qifa_color_id, num: element.num_in_packing }];
    }
    element["suiteTable"] = clear_noval_line(element.suiteTable.dataValue ?? []);

    // 当商品类型配置无颜色，图片跟着货号规格走
    if (props.formConfig.has_color == 0) {
      element["imgs"] = inputRefMap.value[`imgRef_${index}`].getUploadData();
    }

    for (var i in delobjs) {
      delete element[delobjs[i]];
    }
    // if (element.form.qifa_color_id != '251') {
    //   delete element.colorsArr;
    // }
  }

  console.log(JSON.stringify(allArr));

  var letgo = 1;
  for (let index = 0; index < allArr.length; index++) {
    const element = allArr[index];
    console.log(element);
    console.log(element.evergo);

    if (element.evergo == 0) {
      letgo = 0;
      console.log("jjjjjjjjjjjj");
    }
  }

  console.log(letgo);

  if (letgo == 1) {
    for (let index = 0; index < allArr.length; index++) {
      const element = allArr[index];
      delete element.evergo;
      delete element.sku_error;
      if (element.specTable.length < 1) {
        delete element.specTable;
      }
      if (element.suiteTable.length < 1) {
        delete element.suiteTable;
      }
    }

    console.log("后台的规格数据");
    console.log(allArr);
    return Promise.resolve(allArr);
  } else {
    //请修改系统货号规格信息
    ElMessage.error($t("goods_archive.tip_spec_ever_table"));
    return Promise.resolve(false);
  }
};

const resetSpectext = () => {
  specsArr.value = JSON.parse(JSON.stringify(specsArrOld.value));
  initFun();
};

// form ref 集合
const refs = reactive<Array<FormInstance>>([]);

// 暴露的方法
defineExpose({
  get_postdata,
  validate: () => {
    return new Promise<{
      ref?: FormInstance;
      err?: string;
      other?: boolean;
    }>(resolve => {
      Promise.all(
        refs.filter(Boolean).map(ref => {
          return new Promise<{
            ref?: FormInstance;
            err?: string;
            other?: boolean;
          }>(_resolve => {
            ref
              .validate()
              .then(() => {
                _resolve({});
              })
              .catch(error => {
                _resolve({ ref, err: Object.keys(error)?.[0], other: true });
              });
          });
        })
      ).then(arr => {
        resolve(arr.filter(item => !!item.other)?.[0]);
      });
    });
  },

  resetSpec: () => {
    specsArr.value = JSON.parse(JSON.stringify(specsArrOld.value));
    initFun();
    const timer = requestAnimationFrame(() => {
      refs.filter(Boolean).at(0)?.clearValidate();
      cancelAnimationFrame(timer);
    });
  }
});

const modelValue = defineModel<Record<string, any>>({ default: {} });
</script>

<style scoped lang="scss">
.error_red_box {
  background-color: #fff2f3;
  color: var(--el-color-danger);
  line-height: 30px;
  border-radius: 2px;
  margin-left: 0;
  margin-bottom: 10px;
  padding: 0 12px;
}
.size_table_box {
  position: relative;

  .size_plus_all {
    position: absolute;
    right: 10px;
    bottom: 15px;
  }

  .size_plus_all.three {
    right: 180px;
  }
}

.errorTip {
  font-size: 11px;
  color: rgb(228, 15, 15);
  text-align: left;
}

.sku__error {
  color: var(--el-color-danger);
  font-size: 12px;
}

.specs_ever {
  border-radius: 4px;
  border: 1px solid var(--default-input-border);
  margin-bottom: 20px;
  overflow: auto;

  .header {
    padding: 10px 20px;
    background-color: #f8f8fa;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .body {
    padding: 20px;
  }

  :deep(.sku .el-input__wrapper) {
    box-shadow: none;
  }

  :deep(.sku .el-input) {
    border: 0;
  }
}

.error_tip {
  color: var(--el-color-danger);
  font-size: 12px;

  height: 30px;
  line-height: 27px;
  text-align: center;
}

:deep(.header .el-icon) {
  color: var(--el-color-primary);
  font-size: 14px;
  position: relative;
  top: 1px;
}
</style>
<style>
.el-popper.is-light.own_popper_big {
  padding: 20px;

  background: #fff;
}
.editTableMini .miniEdit {
  width: auto;
}
.miniEdit .qf_select,
.miniEdit .qf_select.el-select .el-select__wrapper {
  height: 24px;
  border-bottom: 0;
  box-shadow: 0;
  padding: 0;
  min-height: 24px;
}

.miniEdit .qf_input.el-input .el-input__wrapper,
.miniEdit .el-input__inner {
  height: 24px !important;
  border-bottom: 0;
  box-shadow: 0;
  padding: 0;
}

.miniEdit .merak-control {
  margin-bottom: 0 !important;
}

.miniEdit .merak-control .el-input__wrapper,
.miniEdit .qf_input.el-input {
  border: 0;
}

.miniEdit .el-form-item__label {
  display: none !important;
}

.miniEdit .el-button {
  background-color: #fff;
}
.sku .el-input__prefix-inner {
  position: relative;
  top: -1px;
}
.sizeMini .el-button--default.is-plain:focus,
.el-button--default.is-plain {
  background: #fff !important;
  padding: 3px 25px;
  font-size: 12px;
}
.nooption .editTableMini .miniEdit .minThead > tr > td {
  min-width: 100px;
}
.size_table_box .el-icon.el-input__icon.el-input__validateIcon {
  display: none;
}

/* .nooption .opration.plus{
      display:none;
    }
    .nooption .minBody tr td:nth-child(2){
      background-color: #F3F4F7;
    } */
.create_size_box .qf_input.el-input .el-input__wrapper .el-input__inner {
  line-height: 30px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.create_size_box .el-input__wrapper {
  width: 100%;
}
</style>
